<template>
  <div class="hmi-batch-update-table">
    <!-- 工具栏 -->
    <HmiTableToolbar
      v-if="showToolbar"
      :loading="loading"
      :show-refresh="true"
      :show-export="showExport"
      @refresh="handleRefresh"
      @export="handleExport"
    >
      <template #left>
        <span v-if="config.showSettingZone" class="zone-info">
          定值区激活：{{ settingZoneStore.activeZone }} | 展示：{{ settingZoneStore.displayZone }}
        </span>
      </template>
      <template #right-extra>
        <el-button
          v-if="config.showAutoSetButton"
          type="primary"
          :icon="Switch"
          @click="handleAutoSet"
        >
          自动
        </el-button>
        <el-button
          :type="isEditMode ? 'warning' : 'primary'"
          :icon="isEditMode ? Close : Edit"
          @click="toggleEditMode"
        >
          {{ isEditMode ? "退出编辑" : "进入编辑" }}
        </el-button>
        <el-button
          v-if="isEditMode"
          type="success"
          :icon="Check"
          :disabled="!hasChanges"
          :loading="loading"
          @click="handleSave"
        >
          保存更改
        </el-button>
        <el-button
          v-if="isEditMode && hasChanges"
          type="info"
          :icon="RefreshLeft"
          @click="handleReset"
        >
          重置
        </el-button>
      </template>
    </HmiTableToolbar>

    <!-- 表格 -->
    <el-card shadow="hover" class="hmi-batch-update-table__card">
      <el-table
        :data="tableData"
        :loading="loading"
        highlight-current-row
        border
        table-layout="fixed"
        :row-class-name="tableRowClassName"
        class="hmi-batch-update-table__card__content"
        @selection-change="handleSelectionChange"
      >
        <!--  width="55"  -->
        <!-- 选择列 -->
        <el-table-column v-if="selectable" width="55" type="selection" align="center" />
        <!--           :width="column.width"
          :min-width="column.minWidth || 120" -->
        <!-- 数据列 -->
        <el-table-column
          v-for="column in visibleColumns"
          :key="column.key"
          :prop="column.key"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth || 120"
          align="left"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <HmiTableCell
              v-if="isEditMode && column.key === 'newValue'"
              v-model="row.newValue"
              :column="getColumnConfig(row)"
              :editable="!readonly"
              @change="() => handleValueChange(row, column)"
            />

            <template v-else>
              <el-switch
                v-if="isBooleanColumn(row, column)"
                :model-value="row[column.key]"
                :disabled="true"
                size="small"
                :class="{
                  'changed-value': row._hasChanged,
                  'readonly-switch': true,
                }"
              />
              <span v-else>
                {{ formatCellValue(row, column) }}
              </span>
            </template>
          </template>
        </el-table-column>

        <!--width="100" -->
        <el-table-column v-if="showActions" label="操作" align="center" width="80" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row._hasChanged" type="text" size="small" @click="resetRow(row)">
              重置
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <OffsetPagination
        v-if="total > 0"
        v-model:offset="pagination.offset"
        v-model:limit="pagination.limit"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :layout="paginationLayout"
        class="hmi-batch-update-table__card__pagination"
        @pagination="handlePaginationChange"
      />
    </el-card>

    <!-- 确认对话框 -->
    <el-dialog v-model="showConfirmDialog" title="确认操作" width="400px" append-to-body>
      <p>{{ confirmMessage }}</p>
      <template #footer>
        <el-button @click="showConfirmDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAction">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import { Switch, Edit, Close, Check, RefreshLeft } from "@element-plus/icons-vue";
import { useHmiTableData } from "./composables/useHmiTableData";
import { useTableExport } from "@/composables";
import { isBooleanColumn, createCellFormatter } from "@/utils/hmi-data-table";
import { useSettingZoneStore } from "@/store";
import type { HmiBatchUpdateConfig, HmiColumnConfig, HmiTableRow } from "./types";

interface Props {
  config: HmiBatchUpdateConfig;
  readonly?: boolean;
  showToolbar?: boolean;
  showExport?: boolean;
  showActions?: boolean;
  selectable?: boolean;
}

interface Emits {
  (e: "save-success", data: any): void;
  (e: "save-error", error: Error): void;
  (e: "selection-change", selection: HmiTableRow[]): void;
}

const props = withDefaults(defineProps<Props>(), {
  readonly: false,
  showToolbar: true,
  showExport: true,
  showActions: true,
  selectable: false,
});

const route = useRoute();
const emit = defineEmits<Emits>();
const settingZoneStore = useSettingZoneStore();

// 使用数据管理 composable
const {
  tableData,
  loading,
  total,
  pagination,
  hasChanges,
  fetchData,
  handleValueChange: handleDataChange,
  saveChanges,
  autoSet,
  resetChanges,
  setAutoRefresh,
  cleanupAutoRefresh,
  handlePaginationChange,
  refreshData,
} = useHmiTableData(props.config);

// 使用导出 composable
const { exportToExcel, generateExportColumns } = useTableExport();

// 本地状态
const isEditMode = ref(false);
const selectedRows = ref<HmiTableRow[]>([]);
const showConfirmDialog = ref(false);
const confirmMessage = ref("");
const confirmAction = ref(() => {});

// 分页状态
const currentPage = computed({
  get: () => Math.floor(pagination.offset / pagination.limit) + 1,
  set: (value) => {
    pagination.offset = (value - 1) * pagination.limit;
  },
});

const pageSize = computed({
  get: () => pagination.limit,
  set: (value) => {
    pagination.limit = value;
    pagination.offset = 0;
  },
});

// 可见列
const visibleColumns = computed(() => {
  const columns = [...props.config.columns];
  if (isEditMode.value) {
    // 编辑模式下添加 newValue 列
    // const newValueColumn = {
    //   key: "newValue",
    //   label: "新值",
    //   type: "string" as const,
    //   width: 150,
    // };
    // const insert_index = columns.findIndex((item) => item.key === props.config.valueKey);
    // columns.splice(insert_index, 0, newValueColumn);
  } else {
    // 删除 newValue 列
    const delete_index = columns.findIndex((item) => item.key === "newValue");
    if (delete_index !== -1) {
      columns.splice(delete_index, 1);
    }
  }
  return columns;
});

// 统一的单元格格式化（根据配置动态映射枚举）
const formatCellValue = createCellFormatter({
  valueKey: props.config.valueKey,
  enumKey: props.config.enumKey,
});

const tableRowClassName = ({ row }: { row: any }): string => {
  return row._hasChanged ? "table-edit-row-correct" : "";
};

// 分页布局：与其他模板一致，支持按配置隐藏 sizes
const paginationLayout = computed(() => {
  return props.config.pagination?.showSizeChanger === false
    ? "total, prev, pager, next, jumper"
    : "total, sizes, prev, pager, next, jumper";
});

// 获取列配置
function getColumnConfig(row: HmiTableRow): HmiColumnConfig {
  // 根据行数据动态确定列类型
  const valueType = determineValueType(row);
  if (row["Lower Limit"]) {
    row.min = Number(row["Lower Limit"]);
  }
  if (row["Upper Limit"]) {
    row.max = Number(row["Upper Limit"]);
  }
  if (row["Step"]) {
    row.step = Number(row["Step"]);
  }
  const columns = [...props.config.columns];
  const column = columns.find((item) => item.key === "newValue");
  // console.log(row[props.config.enumKey || ""]);
  return {
    key: "newValue",
    label: "新值",
    type: valueType,
    enumOptions: row[props.config.enumKey || ""] || [],
    fix: column?.fix || 3,
    min: row.min || column?.min,
    max: row.max || column?.max,
    step: row.step || column?.step,
  };
}

// 确定值类型
function determineValueType(row: HmiTableRow): "enum" | "number" | "string" | "boolean" {
  const enumKey = props.config.enumKey;
  const valueKey = props.config.valueKey;

  if (enumKey && Array.isArray(row[enumKey])) {
    return "enum";
  }

  const value = row[valueKey];
  if (typeof value === "boolean") return "boolean";
  if (typeof value === "number") return "number";
  return "string";
}

// 判断是否为 Boolean 列
// function isBooleanColumn(row: HmiTableRow, column: HmiColumnConfig): boolean {
//   const value = row[column.key];
//   return typeof value === "boolean";
// }

// 处理值变更
function handleValueChange(row: HmiTableRow, column: HmiColumnConfig) {
  handleDataChange(row, column);
}

// 自动-调零漂/调系数
async function handleAutoSet() {
  try {
    const result = await autoSet();
    ElMessage.success(result + ", 自动操作成功");
    // emit("save-success", result);
  } catch (error) {
    // const errorMsg = props.config.updateBodyConfig.type == 0 ? "自动调零漂失败" : "自动调系数失败";
    ElMessage.error("自动操作失败，请重试");
    emit("save-error", error as Error);
  }
}

// 切换编辑模式
function toggleEditMode() {
  if (isEditMode.value && hasChanges.value) {
    showConfirm("有未保存的更改，确定要退出编辑模式吗？", () => {
      resetChanges();
      isEditMode.value = false;
      showConfirmDialog.value = false;
    });
  } else {
    isEditMode.value = !isEditMode.value;
  }
}

// 保存
async function handleSave() {
  try {
    const result = await saveChanges();
    // if (result)
    // console.log("handleSave:", result);
    ElMessage.success("保存成功");
    // emit("save-success", result);
    isEditMode.value = false;
    // 保存成功后刷新数据, 间隔 0.2 second
    setTimeout(() => {
      // console.log("执行一次")
      fetchData();
    }, 200);
    // await fetchData();
    // console.log("一次结束")
  } catch (error) {
    ElMessage.error("保存失败");
    emit("save-error", error as Error);
  }
}

// 重置
function handleReset() {
  showConfirm("确定要重置所有更改吗？", async () => {
    await resetChanges();
    showConfirmDialog.value = false;
  });
}

// 刷新
async function handleRefresh() {
  try {
    await refreshData();
    ElMessage.success("刷新成功");
  } catch (error) {
    const errorInstance = error instanceof Error ? error : new Error(String(error));
    console.error("刷新失败:", errorInstance);
    ElMessage.error("刷新失败，请重试");
  }
}

// 导出表格数据
async function handleExport() {
  try {
    if (!tableData.value.length) {
      ElMessage.warning("暂无数据可导出");
      return;
    }

    // 生成导出列配置
    const columns = generateExportColumns(props.config.columns);

    const filename = route.meta.title as string;
    // 导出配置
    const exportConfig = {
      filename: `${filename}-${new Date().toISOString().slice(0, 10)}`,
      sheetName: `${filename}数据`,
      columns,
      data: tableData.value,
    };

    await exportToExcel(exportConfig);
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请重试");
  }
}

// 重置单行
function resetRow(row: HmiTableRow) {
  row.newValue = row._originalValue;
  row._hasChanged = false;
  handleValueChange(row, { key: "newValue" } as HmiColumnConfig);
}

// 选择变更
function handleSelectionChange(selection: HmiTableRow[]) {
  selectedRows.value = selection;
  emit("selection-change", selection);
}

// 分页变更
function handleSizeChange() {
  handlePaginationChange();
}

function handleCurrentChange() {
  handlePaginationChange();
}

// 确认对话框
function showConfirm(message: string, action: () => void) {
  confirmMessage.value = message;
  confirmAction.value = action;
  showConfirmDialog.value = true;
}

// 监听分页变化
watch([() => pagination.offset, () => pagination.limit], () => {
  handlePaginationChange();
  // 打印 config 配置项
  // console.log("当前配置:", props.config);
});

// 监听编辑模式变化，控制自动刷新
watch(isEditMode, (newEditMode) => {
  // 仅在配置明确启用自动刷新时，才根据编辑态切换自动刷新
  if (props.config.enableAutoRefresh === true) {
    setAutoRefresh(!newEditMode);
  }
});

// 组件卸载时清理自动刷新
onUnmounted(() => {
  // 始终清理，防止定时器残留导致持续请求
  cleanupAutoRefresh();
});

// 初始化时根据编辑模式设置自动刷新
onMounted(() => {
  // 仅当配置明确开启时才注册自动刷新
  if (props.config.enableAutoRefresh === true && !isEditMode.value) {
    setAutoRefresh(true);
  }
});
</script>

<style lang="scss" scoped>
.hmi-batch-update-table {
  // width: 100%;
  &__toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 12px;
    background: #f5f5f5;
    border-radius: 4px;

    &__left {
      flex: 1;
    }

    &__right {
      display: flex;
      gap: 8px;
    }
  }

  &__card {
    &__content {
      width: 100%;
    }

    &__pagination {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.zone-info {
  color: #666;
  font-size: 14px;
}

.text-orange-500 {
  color: #f59e0b;
  font-weight: 500;
}

/* Boolean 开关样式 */
.readonly-switch {
  pointer-events: none;
}

.changed-value {
  /* 为修改过的值添加特殊样式 */
  box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.3);
  border-radius: 12px;
}

/* 隐藏水平滚动条 */
:deep(.el-scrollbar__bar.is-horizontal) {
  display: none !important;
}

/* 隐藏垂直滚动条 */
:deep(.el-scrollbar__bar.is-vertical) {
  display: none !important;
}
</style>
